<?php

require __DIR__ . '/../vendor/autoload.php';

$app = require_once __DIR__ . '/../bootstrap/app.php';

$app->make(\App\Console\Kernel::class)->bootstrap();

/* ============== Write Codes Below ================= */

$dupUsers = \App\Models\FrontendUser::query()
    ->select('agent_id', 'mobile', \Illuminate\Support\Facades\DB::raw('count(*) as count'))
    ->groupBy(['agent_id', 'mobile'])
    ->orderByDesc('count')
    ->having(DB::raw('count(*)'), '>', 1)
    ->get();

echo '共有' . $dupUsers->count() . '条数据需要清理' . PHP_EOL;

/** @var \App\Models\FrontendUser $user */
foreach ($dupUsers as $user) {
    $agentId = $user->agent_id;
    $agentName = $user->agent ? $user->agent->name : $user->agent_id;
    $mobile = $user->mobile;

    echo sprintf('# 手机号:%s ,所属代理:%s, ,用户数量: %s', $mobile, $agentName, $user->count) . PHP_EOL;
    //查询手机号对应的所有用户
    $users = \App\Models\FrontendUser::query()
        ->where('agent_id', $agentId)
        ->where('mobile', $mobile)
        ->get();
    foreach ($users as $index => $user) {
        //保留第一个
        if (0 === $index) {
            echo sprintf('    [K]用户ID:%s, 第一个用户保留', $user->id) . PHP_EOL;

            continue;
        }
        // 其它用户查询是否有订单和资产，没有则删除用户
        $orderCount = \App\Models\Order::query()->where('user_id', $user->id)->count();
        $assetCount = \App\Models\Asset::query()->where('user_id', $user->id)->count();
        echo sprintf('    [D]用户ID:%s, 订单数量:%s 资产数量:%s', $user->id, $orderCount, $assetCount);
        if (0 === $orderCount && 0 === $assetCount) {
            $user->delete();
            echo ', 删除成功' . PHP_EOL;
        } else {
            echo ', 删除失败' . PHP_EOL;
        }
    }
}
